package com.example.servletdemo.servlet.ajax;

import com.alibaba.fastjson.JSON;
import com.example.servletdemo.model.Result;
import com.example.servletdemo.model.User;
import com.sun.xml.internal.ws.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet("/UserLogin2Servlet")
public class UserLogin2Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        //解析参数
        InputStreamReader insr = new InputStreamReader(req.getInputStream(),"utf-8");
        String res = "";
        int respInt = insr.read();
        while(respInt!=-1) {
            res +=(char)respInt;
            respInt = insr.read();
        }
        User user=JSON.parseObject(res,User.class);
        //返回结果
        Result result = new Result();
        if(user.getUsername().isEmpty()||user.getPassword().isEmpty()){
            result.setSuccess(false);
            result.setErrorCode(-1);
            result.setErrorMsg("用户名或者密码请输入完整");
        }else if(!user.getUsername().equals("admin")||!user.getPassword().equals("admin")){
            result.setSuccess(false);
            result.setErrorCode(-2);
            result.setErrorMsg("用户名或者密码错误");
        }else {
            //登录成功
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            //授权密码
            jedis.auth("888888");
            String token= UUID.randomUUID().toString();
            System.out.println("登录成功，uuid:"+token);
//            jedis.setex(token,60*30,JSON.toJSONString(user));
            jedis.setex(token,30,JSON.toJSONString(user));
            jedis.close();

            //设置cookie
            Cookie cookie = new Cookie("token", token);
            int COOKIE_EXPIRE_TIME=60;//cookie或者redis缓存的有效时间  单位秒
//            cookie.setMaxAge(COOKIE_EXPIRE_TIME);//设置cookie时间
            cookie.setPath("/");
            resp.addCookie(cookie);

            //返回token
            result.setObject(token);
            result.setSuccess(true);
        }
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(result));
    }
}
